from flask import Blueprint, current_app, request
from app.utils.response_util import ResponseUtil

bp = Blueprint('cultural_item', __name__, url_prefix='/api/cultural_item')

@bp.route('/<item_id>', methods=['GET'])
def get_cultural_item(item_id):
    """根据 ID 获取文物信息"""
    try:
        with current_app.neo4j_driver.session() as session:
            result = session.run("""
                MATCH (ci:CulturalItem {id: $id}) 
                RETURN ci
            """, id=item_id)
            
            item = result.single()
            if not item:
                return ResponseUtil.error("未找到指定文物", status_code=404)
                
            return ResponseUtil.success(data=dict(item['ci']))
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/search', methods=['GET'])
def search_cultural_items():
    """搜索文物"""
    try:
        node_service = current_app.node_service
        keyword = request.args.get('name')
        
        if not keyword:
            return ResponseUtil.missing_params("缺少搜索关键词")
            
        items = node_service.search_cultural_items(keyword)
        return ResponseUtil.success(data=items)
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/gene/<gene_name>', methods=['GET'])
def get_gene_data(gene_name):
    """根据基因名称获取相关文物信息"""
    try:
        with current_app.neo4j_driver.session() as session:
            result = session.run("""
                MATCH (ci:CulturalItem)-[:HAS_GENE]->(g:Gene {name: $gene_name})
                RETURN ci, g
            """, gene_name=gene_name)

            items = []
            for record in result:
                items.append({
                    "cultural_item": dict(record['ci']),
                    "gene": dict(record['g'])
                })

            return ResponseUtil.success(data=items)
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/data/artifact-meaning', methods=['GET'])
def get_artifact_meaning():
    """获取文物含义信息"""
    try:
        with current_app.neo4j_driver.session() as session:
            result = session.run("""
                MATCH (a:CulturalItem)-[r:HAS_MEANING]->(m:Meaning)
                RETURN a, r, m
            """)
            
            nodes = []
            links = []
            seen_nodes = set()
            
            for record in result:
                artifact, meaning = record['a'], record['m']
                
                # 修改节点数据结构，确保包含必要的属性
                if artifact.element_id not in seen_nodes:
                    nodes.append({
                        'element_id': artifact.element_id,
                        'labels': list(artifact.labels),
                        'properties': {
                            'name': artifact.get('name', '未命名'),
                            'description': artifact.get('description', ''),
                            **dict(artifact)
                        }
                    })
                    seen_nodes.add(artifact.element_id)
                
                if meaning.element_id not in seen_nodes:
                    nodes.append({
                        'element_id': meaning.element_id,
                        'labels': list(meaning.labels),
                        'properties': {
                            'mean': meaning.get('mean', ''),
                            **dict(meaning)
                        }
                    })
                    seen_nodes.add(meaning.element_id)
                
                links.append({
                    'source': artifact.element_id,
                    'target': meaning.element_id,
                    'type': type(record['r']).__name__
                })
            
            return ResponseUtil.success(data={'nodes': nodes, 'links': links})
    except Exception as e:
        return ResponseUtil.error(str(e))

@bp.route('/data/artifact-story', methods=['GET'])
def get_artifact_story():
    """获取文物故事信息"""
    try:
        with current_app.neo4j_driver.session() as session:
            result = session.run("""
                MATCH (a:CulturalItem)-[r:HAS_STORY]->(s:Story)
                WHERE s.content IS NOT NULL
                RETURN a, r, s
            """)
            
            nodes = []
            links = []
            seen_nodes = set()
            
            for record in result:
                artifact, story = record['a'], record['s']
                
                if artifact.element_id not in seen_nodes:
                    nodes.append({
                        'element_id': artifact.element_id,
                        'labels': list(artifact.labels),
                        'properties': dict(artifact)
                    })
                    seen_nodes.add(artifact.element_id)
                
                if story.element_id not in seen_nodes:
                    nodes.append({
                        'element_id': story.element_id,
                        'labels': list(story.labels),
                        'properties': dict(story)
                    })
                    seen_nodes.add(story.element_id)
                
                links.append({
                    'source': artifact.element_id,
                    'target': story.element_id,
                    'type': type(record['r']).__name__
                })
            
            return ResponseUtil.success(data={'nodes': nodes, 'links': links})
    except Exception as e:
        return ResponseUtil.error(str(e))